package com.christina.engine.execution.impl;

import com.christina.engine.execution.AbstractServiceExecutor;
import com.christina.engine.execution.model.ExecutionRequest;
import com.christina.engine.execution.model.ExecutionResult;
import com.christina.service.domain.user.UserDomainService;
import com.christina.engine.context.model.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 用户服务执行器
 * 负责执行用户相关的业务逻辑
 * 
 * @author Christina
 */
@Slf4j
@Component
public class UserServiceExecutor extends AbstractServiceExecutor {
    
    private final UserDomainService userDomainService;
    
    public UserServiceExecutor(UserDomainService userDomainService) {
        super("UserServiceExecutor", new String[]{"USER", "PROFILE"}, 300);
        this.userDomainService = userDomainService;
    }
    
    @Override
    protected ExecutionResult doExecute(ExecutionRequest request) {
        log.debug("Executing user service for request: {}", request.getRequestId());
        
        try {
            // 验证参数
            validateUserParameters(request);
            
            String action = request.getParameter("action", String.class);
            if (action == null) {
                action = "profile";
            }
            
            return switch (action) {
                case "profile" -> getUserProfile(request);
                case "update" -> updateUserProfile(request);
                case "preferences" -> updateUserPreferences(request);
                case "statistics" -> getUserStatistics(request);
                case "context" -> getUserContext(request);
                default -> ExecutionResult.failure("Unsupported user action: " + action, getName());
            };
                    
        } catch (Exception e) {
            log.error("Error executing user service", e);
            return ExecutionResult.failure("Failed to process user request: " + e.getMessage(), e, getName());
        }
    }
    
    /**
     * 验证用户参数
     */
    private void validateUserParameters(ExecutionRequest request) {
        Long userId = request.getParameter("userId", Long.class);
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("Valid user ID is required");
        }
    }
    
    /**
     * 获取用户资料
     */
    private ExecutionResult getUserProfile(ExecutionRequest request) {
        Long userId = request.getParameter("userId", Long.class);
        UserContext userContext = userDomainService.getUserContext(userId);
        
        if (userContext == null) {
            return ExecutionResult.failure("User not found", getName());
        }
        
        return ExecutionResult.success(Map.of(
                "userId", userContext.getUserId(),
                "username", userContext.getUsername(),
                "role", userContext.getRole(),
                "status", userContext.getStatus(),
                "lastActiveTime", userContext.getLastActiveTime(),
                "attributes", userContext.getAttributes() != null ? userContext.getAttributes() : Map.of()
        ), getName());
    }
    
    /**
     * 更新用户资料
     */
    private ExecutionResult updateUserProfile(ExecutionRequest request) {
        Long userId = request.getParameter("userId", Long.class);
        UserContext currentContext = userDomainService.getUserContext(userId);
        
        if (currentContext == null) {
            return ExecutionResult.failure("User not found", getName());
        }
        
        // 构建更新的用户上下文
        UserContext.UserContextBuilder builder = currentContext.toBuilder();
        
        String username = request.getParameter("username", String.class);
        if (username != null) {
            builder.username(username);
        }
        
        String role = request.getParameter("role", String.class);
        if (role != null) {
            builder.role(role);
        }
        
        String status = request.getParameter("status", String.class);
        if (status != null) {
            builder.status(status);
        }
        
        Map<String, Object> attributes = request.getParameter("attributes", Map.class);
        if (attributes != null) {
            builder.attributes(attributes);
        }
        
        UserContext updatedContext = builder.build();
        boolean success = userDomainService.updateUserContext(updatedContext);
        
        return ExecutionResult.success(Map.of(
                "success", success,
                "message", success ? "User profile updated successfully" : "Failed to update user profile"
        ), getName());
    }
    
    /**
     * 更新用户偏好
     */
    private ExecutionResult updateUserPreferences(ExecutionRequest request) {
        Long userId = request.getParameter("userId", Long.class);
        UserContext currentContext = userDomainService.getUserContext(userId);
        
        if (currentContext == null) {
            return ExecutionResult.failure("User not found", getName());
        }
        
        // 构建更新的偏好设置
        UserContext.UserPreferences.UserPreferencesBuilder prefsBuilder = 
                currentContext.getPreferences() != null ? 
                        currentContext.getPreferences().toBuilder() : 
                        UserContext.UserPreferences.builder();
        
        String language = request.getParameter("language", String.class);
        if (language != null) {
            prefsBuilder.language(language);
        }
        
        String theme = request.getParameter("theme", String.class);
        if (theme != null) {
            prefsBuilder.theme(theme);
        }
        
        String timezone = request.getParameter("timezone", String.class);
        if (timezone != null) {
            prefsBuilder.timezone(timezone);
        }
        
        Boolean notifications = request.getParameter("notifications", Boolean.class);
        if (notifications != null) {
            prefsBuilder.notifications(notifications);
        }
        
        UserContext updatedContext = currentContext.toBuilder()
                .preferences(prefsBuilder.build())
                .build();
        
        boolean success = userDomainService.updateUserContext(updatedContext);
        
        return ExecutionResult.success(Map.of(
                "success", success,
                "message", success ? "User preferences updated successfully" : "Failed to update user preferences"
        ), getName());
    }
    
    /**
     * 获取用户统计
     */
    private ExecutionResult getUserStatistics(ExecutionRequest request) {
        Long userId = request.getParameter("userId", Long.class);
        Object statistics = userDomainService.getUserStatistics(userId);
        
        return ExecutionResult.success(statistics, getName());
    }
    
    /**
     * 获取用户上下文
     */
    private ExecutionResult getUserContext(ExecutionRequest request) {
        Long userId = request.getParameter("userId", Long.class);
        UserContext userContext = userDomainService.getUserContext(userId);
        
        if (userContext == null) {
            return ExecutionResult.failure("User context not found", getName());
        }
        
        return ExecutionResult.success(userContext, getName());
    }
}